package com.qianfan.hellokotlin.service.impl

import com.qianfan.hellokotlin.entity.Message
import com.qianfan.hellokotlin.repository.MessageRepository
import com.qianfan.hellokotlin.service.MessageService
import org.springframework.data.repository.CrudRepository
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Service
import java.util.*

@Service
class MessageServiceImpl(val db: JdbcTemplate) : MessageService {
    override fun findMessages(): List<Message> = db.query("select * from messages") { response, _ ->
            Message(response.getString("id"), response.getString("text"))
    }

    override fun findMessageById(id: String): List<Message> = db.query("select * from messages where id = '$id'") { response, _ ->
        Message(response.getString("id"), response.getString("text"))
    }

    override fun save(message: Message){
        db.update("insert into messages(text) values ( ? )",
            message.text)
    }
}

@Service
class MessageRepositoryService(val db: MessageRepository) {
    fun findMessages(): List<Message> = db.findAll().toList()

    fun findMessageById(id: String): List<Message> = db.findById(id).toList()

    fun save(message: Message) {
        db.save(message)
    }

    fun <T : Any> Optional<out T>.toList(): List<T> =
        if (isPresent) listOf(get()) else emptyList()
}